//
//  HDCFFundListVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/10/31.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFFundListVc.h"
#import "HDCFFundCell.h"
#import "YYModel.h"
#import "HDCFFundDetailVc.h"
#import "MJRefresh.h"
#import "SVProgressHUD.h"

#define KFundList @"/public/product/batch-get-fund-info"

@interface HDCFFundListVc ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, weak) UITableView *fundList;
@property (nonatomic, strong) NSMutableArray *fundArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *searchKey;
@property (nonatomic, weak) UITextField *field;

@end

@implementation HDCFFundListVc

- (NSMutableArray *)fundArray{
    if (!_fundArray) {
        self.fundArray = [NSMutableArray array];
    }
    return _fundArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.navigationItem setTitle:@"基金列表"];
    self.page = 1;
    UITextField *textField = [[UITextField alloc] init];
    self.field = textField;
    textField.frame = CGRectMake(10, 10, screenWidth - 20, 30);
    [self.view addSubview:textField];
    textField.delegate = self;
    [self setSearchBarWithTextFild:textField];
    
    UIButton *searchB = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchB.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [searchB setTitle:@"搜索" forState:UIControlStateNormal];
    [searchB setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    searchB.frame = CGRectMake(screenWidth - 60, 10, 60, 30);
    searchB.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [searchB addTarget:self action:@selector(searchBarClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchB];
    
    CGRect listFrame = CGRectMake(0, CGRectGetMaxY(textField.frame) + 5, screenWidth, screenHeight - CGRectGetMaxY(textField.frame) + 5 - KNavHeight);
    UITableView *fundList = [[UITableView alloc] initWithFrame:listFrame style:UITableViewStylePlain];
    self.fundList = fundList;
    fundList.delegate = self;
    fundList.dataSource = self;
    fundList.tableFooterView =  [[UIView alloc] initWithFrame:CGRectZero];
    fundList.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(mainRefresh)];
    fundList.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(mainLoadMore)];
    [self.view addSubview:fundList];
    
    [self getDataOne];
    
}

- (void)searchBarClick{
    if (self.field.text.length > 0) {
        [self.field endEditing:YES];
        self.searchKey = self.field.text;
        [self.fundArray removeAllObjects];
        [self getDataOne];
    }else{
        self.field.placeholder = @"请输入查询条件";
        if (self.searchKey.length > 0) {
            self.searchKey = nil;
            [self getDataOne];
            [self.field endEditing:YES];
        }else{
            self.searchKey = nil;
            [self.field endEditing:YES];
        }
        
    }
}

- (void)mainRefresh{
    self.page = 1;
    [self.fundArray removeAllObjects];
    [self getData];
}

- (void)mainLoadMore{
    self.page++;
    [self getData];
}

- (void)getDataOne{
    [SVProgressHUD show];
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
//    paramets[@"fundCodes"] = @"";
    paramets[@"isBuyEnable"] = @"0";
//    paramets[@"isQDII"] = @"";
//    paramets[@"isMMFund"] = @"1";
//    paramets[@"isRecommended"] = @"";
    paramets[@"sort"] = @"DESC";
    paramets[@"period"] = @"year1";
//    paramets[@"geographicalSector"] = @"";
//    paramets[@"specializeSector"] = @"";
//    paramets[@"fundType"] = @"";
//    paramets[@"shortName"] = @"";
//    paramets[@"fundHouseCode"] = @"";
    if (self.searchKey.length > 0) {
        paramets[@"search"] = self.searchKey;
    }
    paramets[@"pageSize"] = @"10";
    paramets[@"pageIndex"] = [NSString stringWithFormat:@"%ld", self.page];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{@"paramList":jsonStr,
                              @"methodPath":KFundList};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dataDict = result[@"data"];
            [self.fundArray addObjectsFromArray:dataDict[@"data"]];
            NSArray *array = dataDict[@"data"];
            if (array.count < 10) {
                [self.fundList.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.fundList.mj_footer endRefreshing];
            }
            [self.fundList reloadData];
            [self.fundList setContentOffset:CGPointMake(0, 0) animated:NO];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}



- (void)getData{
    
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
//    paramets[@"fundCodes"] = @"";
    paramets[@"isBuyEnable"] = @"0";
//    paramets[@"isQDII"] = @"";
//    paramets[@"isMMFund"] = @"";
//    paramets[@"isRecommended"] = @"";
    paramets[@"sort"] = @"DESC";
    paramets[@"period"] = @"year1";
    if (self.searchKey.length > 0) {
        paramets[@"search"] = self.searchKey;
    }
//    paramets[@"geographicalSector"] = @"";
//    paramets[@"specializeSector"] = @"";
//    paramets[@"fundType"] = @"";
//    paramets[@"shortName"] = @"";
//    paramets[@"fundHouseCode"] = @"";
//    paramets[@"search"] = @"";
    paramets[@"pageSize"] = @"10";
    paramets[@"pageIndex"] = [NSString stringWithFormat:@"%ld", self.page];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KFundList};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
//            [SVProgressHUD showSuccessWithStatus:result[@"message"]];
            NSDictionary *dataDict = result[@"data"];
            [self.fundArray addObjectsFromArray:dataDict[@"data"]];
            if (self.fundArray.count < 10) {
                [self.fundList.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.fundList.mj_footer endRefreshing];
            }
            [self.fundList reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
        [self.fundList.mj_header endRefreshing];
    } failure:^(NSError *errer) {
        [self.fundList.mj_footer endRefreshing];
        [self.fundList.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
  NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void)setSearchBarWithTextFild:(UITextField *)textField{
    textField.returnKeyType =  UIReturnKeySearch;
    textField.font = [UIFont systemFontOfSize:15];
    [textField setFont:[UIFont systemFontOfSize:14]];
    textField.placeholder = @"基金名称或者基金代码";
    [textField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    // 提前在Xcode上设置图片中间拉伸
    textField.background = [UIImage imageNamed:@"bar_search"];
    
    // 通过init初始化的控件大多都没有尺寸
    UIImageView *searchIcon = [[UIImageView alloc] init];
    searchIcon.image = [UIImage imageNamed:@"icon_search"];
    // contentMode：default is UIViewContentModeScaleToFill，要设置为UIViewContentModeCenter：使图片居中，防止图片填充整个imageView
    searchIcon.contentMode = UIViewContentModeCenter;
    searchIcon.size = CGSizeMake(30, 30);
    
    textField.leftView = searchIcon;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    textField.placeholder = nil;
}

-(BOOL)textFieldShouldReturn:(UITextField*)textField{
    
    if (textField.text.length > 0) {
        [textField endEditing:YES];
        self.searchKey = textField.text;
        self.page = 1;
        [self.fundArray removeAllObjects];
        
        [self getDataOne];
    }else{
        textField.placeholder = @"基金名称或者代码";
        if (self.searchKey.length > 0) {
            self.searchKey = nil;
            [self getDataOne];
            [textField endEditing:YES];
        }else{
            self.searchKey = nil;
            [textField endEditing:YES];
        }
        
    }
    return YES;
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.fundArray.count;
    
//     return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"cellId";
    HDCFFundCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [HDCFFundCell HDCFFundCell];
    }
    NSDictionary *dict = self.fundArray[indexPath.row];
    cell.dataDict = dict;
    cell.preservesSuperviewLayoutMargins = NO;
    cell.separatorInset = UIEdgeInsetsZero;
    cell.layoutMargins = UIEdgeInsetsZero;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = self.fundArray[indexPath.row];
    HDCFFundDetailVc *fundDetail = [[HDCFFundDetailVc alloc] init];
    fundDetail.dataDict = dict;
    [self.navigationController pushViewController:fundDetail animated:YES];
}

@end
